package service

import (
	"bgs/cache/redisImp"
	op "bgs/cache/op"
	inventory "bgs/grpc/gen/proxy2/inventory"
	"bgs/conf"
	"bgs/db"
	"bgs/grpc/client"
	"bgs/util"
	"context"
	"fmt"
	"go.uber.org/zap"
)

// WarehouseServiceImp warehouse bizlogic
type WarehouseServiceImp struct {
	dao    *db.PgDao
	slog   *zap.SugaredLogger
	vars   *conf.VarsSection
	proxy  *client.GrpcClientProxy
	cacher *cache.Adapter
}

// NewWarehouseService initialization
func NewWarehouseService(
	pgdao *db.PgDao,
	slog *zap.SugaredLogger,
	vars *conf.VarsSection,
	proxy *client.GrpcClientProxy,
	adp *cache.Adapter,
) *WarehouseServiceImp {
	return &WarehouseServiceImp{
		dao:    pgdao,
		slog:   slog.With("module", "WarehouseService"),
		vars:   vars,
		proxy:  proxy,
		cacher: adp,
	}
}


// genInventoryToken 生成仓库webToken
func (s *WarehouseServiceImp) genInventoryToken(ctx context.Context, brandID int64) (webTokenPtr *inventory.WebToken, err error) {

	cBrand := s.cacher.FetchBrand(brandID)
	if cBrand == nil {
		err = fmt.Errorf("not found brand of brandID:%d", brandID)
		return
	}
	sgID := cBrand.SgID
	ownUserID := cBrand.Ext.OwnUserID
	var empIDOfBrandOwnUser int64
	brandAdminsCached := util.Filter(util.ToGenericSlice(cBrand.Admins), func(v interface{}) bool {
		val := v.(*op.BrandAdminCachedValue)
		return val.UserID == ownUserID
	})
	if len(brandAdminsCached) != 1 {
		err = fmt.Errorf("brand own user not equal 1")
		return
	}

	empIDOfBrandOwnUser = (brandAdminsCached[0].(*op.BrandAdminCachedValue)).EmpID
	
	if empIDOfBrandOwnUser == 0 {
		err = fmt.Errorf("brand own user without employee")
		return
	}

	webTokenPtr = &inventory.WebToken{
		SgId:  uint32(sgID),
		EmpId: uint32(empIDOfBrandOwnUser),
	}
	return
}